import React, {Component} from 'react';
import {Row, Col, Button, Table, message, Spin, Modal, Input, Form} from 'antd';
import './Role.less';
import ajax from '../../util/AjaxUtil';
import qs from 'qs';

class Role extends Component {

    constructor(props) {
        super(props);

        this.state = {
            pageLoading: false,
            roleList: [],
            roleLoading: false,
            roleSelectedRowKeys: [],
            menuTableData: [],
            menuIsLoading: false,
            menuExpandedRowKeys: [],
            menuSelectedRowKeys: [],
            roleModel: {
                title: '',
                cancelText: '取消',
                okText: '确认',
                roleName: '',
                visible: false
            }
        };

        this.addRoleClick = this.addRoleClick.bind(this);
        this.updateRoleClick = this.updateRoleClick.bind(this);
        this.deleteRoleClick = this.deleteRoleClick.bind(this);
        this.roleNameChange = this.roleNameChange.bind(this);
        this.hideRoleModal = this.hideRoleModal.bind(this);
        this.editRole = this.editRole.bind(this);
    }

    render() {

        const columns = [{
            title: '角色名',
            dataIndex: 'name',
            key: 'name',
        }];

        let menuColumns = [{
            title: '菜单名称',
            dataIndex: 'name',
            key: 'name',
        }, {
            title: '菜单id',
            dataIndex: 'id',
            key: 'id',
        }, {
            title: '菜单类型',
            dataIndex: 'type',
            key: 'type',
            render: (record) => {
                if (record === 0) {
                    return '菜单';
                } else if (record === 1) {
                    return '资源';
                }
            }
        }, {
            title: '父类菜单id',
            dataIndex: 'prentId',
            key: 'prentId'
        }];

        let instance = this;

        return (
            <Spin spinning={this.state.pageLoading} delay={300}>
                <Row className={"role-page"}>
                    <Col span={6}>
                        <Button className={"btn-add-role"}
                                type="primary"
                                icon="plus"
                                size="small"
                                onClick={this.addRoleClick}
                        >添加</Button>
                        <Button className={"btn-add-role"}
                                type="primary"
                                icon="edit"
                                size="small"
                                onClick={this.updateRoleClick}
                        >修改</Button>
                        <Button className={"btn-add-role"}
                                type="danger"
                                icon="delete"
                                size="small"
                                onClick={this.deleteRoleClick}
                        >删除</Button>
                        <Table bordered={true}
                               loading={this.state.roleLoading}
                               pagination={false}
                               size={"small"}
                               dataSource={this.state.roleList}
                               columns={columns}
                               rowSelection={{
                                   fixed: true,
                                   type: 'radio',
                                   selectedRowKeys: this.state.roleSelectedRowKeys
                               }}
                               onRow={(record) => {
                                   return {
                                       onClick: () => {
                                           instance.setState({pageLoading: true});
                                           //获取角色拥有的菜单
                                           ajax.post("/userCenter/role/findMenuId", qs.stringify({roleId: record.key}))
                                               .then((resource) => {
                                                   let newState = {
                                                       roleSelectedRowKeys: [record.key],
                                                       pageLoading: false
                                                   };
                                                   if (resource.data) {
                                                       newState.menuSelectedRowKeys = resource.data;
                                                   }
                                                   instance.setState(newState);
                                               })
                                               .catch((error) => {
                                                   message.error("获取数据失败");
                                                   instance.setState({pageLoading: false});
                                               });
                                       }
                                   }
                               }}
                        />
                        <Modal
                            visible={this.state.roleModel.visible}
                            title={this.state.roleModel.title}
                            okText={'确认'}
                            cancelText={'取消'}
                            closable={false}
                            onCancel={this.hideRoleModal}
                            onOk={this.editRole}
                        >
                            <Input placeholder="角色名称"
                                   value={this.state.roleModel.roleName}
                                   onChange={this.roleNameChange}/>
                        </Modal>
                    </Col>
                    <Col span={18}>
                        <Table
                            style={{marginLeft:5}}
                            columns={menuColumns}
                            dataSource={this.state.menuTableData}
                            size={"small"}
                            pagination={false}
                            rowKey={(record) => (record.id)}
                            loading={this.state.menuIsLoading}
                            defaultExpandAllRows={true}
                            expandedRowKeys={this.state.menuExpandedRowKeys}
                            rowSelection={{
                                fixed: true,
                                type: 'checkbox',
                                selectedRowKeys: this.state.menuSelectedRowKeys,
                                onSelect: (record, selected, selectedRows, nativeEvent) => {
                                    let selectedRowKeys = [...instance.state.menuSelectedRowKeys];
                                    if (selected) {
                                        //判断其父菜单是否选中,如果没有选中,将其选中
                                        let parentIds = [];
                                        instance.findParentId(record.id, parentIds);
                                        for (let pKey in parentIds) {
                                            let index = selectedRowKeys.findIndex(k => k === parentIds[pKey]);
                                            if (index === -1) {
                                                selectedRowKeys.push(parentIds[pKey]);
                                            }
                                        }
                                    } else {
                                        let index = -1;
                                        while ((index = selectedRowKeys.findIndex(key => key === record.id)) !== -1) {
                                            selectedRowKeys.splice(index, 1);
                                        }
                                    }

                                    if (this.state.roleSelectedRowKeys.length === 0) {
                                        message.info("请选择角色");
                                        return;
                                    }

                                    //提交数据保存
                                    let param = qs.stringify({
                                        roleId: this.state.roleSelectedRowKeys[0],
                                        menuIds: selectedRowKeys.length === 0 ? [-1] : selectedRowKeys
                                    }, {indices: false});
                                    instance.setState({pageLoading: true});
                                    ajax.post("/userCenter/role/updateMenu", param)
                                        .then((resource) => {
                                            let newState = {pageLoading: false};
                                            if (resource.data.result) {
                                                newState.menuSelectedRowKeys = selectedRowKeys;
                                                message.success("已保存");
                                            } else {
                                                message.error("修改失败");
                                            }
                                            instance.setState(newState);
                                        })
                                        .catch((error) => {
                                            message.error("修改失败");
                                            instance.setState({pageLoading: false});
                                        });
                                }
                            }}
                            onExpand={(expanded, record) => {
                                let expandedRowKeys = [...instance.state.menuExpandedRowKeys];
                                if (expanded) {
                                    expandedRowKeys.push(record.id);
                                } else {
                                    let index = -1;
                                    while ((index = expandedRowKeys.findIndex(key => key === record.id)) !== -1) {
                                        expandedRowKeys.splice(index, 1);
                                    }
                                }
                                instance.setState({menuExpandedRowKeys: expandedRowKeys});
                            }}
                        />
                    </Col>
                </Row>
            </Spin>
        )
    }

    componentDidMount() {
        this.finaAllRole();
        this.findAllMenu();
    }

    finaAllRole() {
        let instance = this;

        //获取所有角色
        this.setState({roleLoading: true});
        ajax.post("/userCenter/role/findAllRole")
            .then((resource) => {
                resource.data.map((item) => {
                    item.key = item.id;
                    return item;
                });
                instance.setState({
                    roleList: resource.data,
                    roleLoading: false
                });
            })
            .catch((error) => {
                message.error("获取数据失败");
                this.setState({roleLoading: false});
            });
    }

    findAllMenu() {
        let instance = this;

        //获取所有的菜单
        this.setState({menuIsLoading: true});
        ajax.post("/userCenter/menu/getTreeData").then((resource) => {
            let expandedRowKeys = [];
            instance.selectExpandedRowKeys(resource.data.children, expandedRowKeys);
            this.setState({
                menuIsLoading: false,
                menuTableData: resource.data.children,
                menuExpandedRowKeys: expandedRowKeys
            });
        }).catch((error) => {
            this.setState({menuIsLoading: false});
            message.error("获取数据失败")
        });
    }

    selectExpandedRowKeys(data, expandedRowKeys) {
        data.map((item) => {
            if (item.children) {
                expandedRowKeys.push(item.id);
                this.selectExpandedRowKeys(item.children, expandedRowKeys);
            }
            return item;
        });
    }

    findParentId(id, parentIds) {
        let item = this.findMenu(id);
        parentIds.push(item.id);
        if (item.prentId) {
            this.findParentId(item.prentId, parentIds);
        }
    }

    findMenu(id) {
        let menu = [];
        this.eachMenu(id, this.state.menuTableData, menu);
        return menu.length > 0 ? menu[0] : null;
    }

    eachMenu(id, data, menu) {
        data.map((item) => {
            if (item.id === id) {
                menu.push(item);
            } else {
                if (item.children && item.children.length > 0) {
                    this.eachMenu(id, item.children, menu);
                }
            }
            return item;
        });
    }

    addRoleClick() {
        this.setState({
            roleModel: {title: '添加角色', visible: true}
        });
    }

    updateRoleClick() {
        if (this.state.roleSelectedRowKeys.length === 0) {
            message.warning("请选择角色");
            return;
        }

        let role = null;
        this.state.roleList.map((item) => {
            if (item.id === this.state.roleSelectedRowKeys[0]) {
                role = item;
            }
            return item;
        });
        this.setState({
            roleModel: {
                title: '修改角色',
                visible: true,
                roleName: role.name
            }
        });
    }

    deleteRoleClick() {
        if (this.state.roleSelectedRowKeys.length === 0) {
            message.warning("请选择角色");
            return;
        }

        let role = null;
        this.state.roleList.map((item) => {
            if (item.id === this.state.roleSelectedRowKeys[0]) {
                role = item;
            }
            return item;
        });

        let instance = this;

        Modal.confirm({
            cancelText: '取消',
            okText: '确定',
            title: '是否删除角色:' + role.name + '?',
            onOk: (close) => {
                ajax.post("/userCenter/role/delete", qs.stringify({
                    id: role.id
                }))
                    .then((resource) => {
                        if (resource.data.result) {
                            message.success("删除成功");
                            close();
                            instance.finaAllRole();
                        } else {
                            message.error("删除失败");
                        }
                    })
                    .catch((error) => {
                        message.error("删除失败");
                    });
            }
        });
    }

    roleNameChange(e) {
        this.setState({
            roleModel: {
                roleName: e.target.value,
                visible: true,
                title: this.state.roleModel.title
            }
        });
    }

    hideRoleModal() {
        this.setState({
            roleModel: {visible: false}
        });
    }

    editRole() {
        if (this.state.roleModel.roleName === null || this.state.roleModel.roleName.length === 0) {
            message.warning("角色名不能为空");
            return;
        }
        if (this.state.roleModel.title === '添加角色') {
            this.addRole();
        } else if (this.state.roleModel.title === '修改角色') {
            this.updateRole();
        }
    }

    addRole() {
        let instance = this;
        instance.pageLoading(true);
        ajax.post('/userCenter/role/create', qs.stringify({
            name: this.state.roleModel.roleName
        }))
            .then((resource) => {
                instance.pageLoading(false);
                if (resource.data.result) {
                    message.info("添加成功");
                    instance.hideRoleModal();
                    instance.finaAllRole();
                } else {
                    message.error("添加失败");
                }
            })
            .catch((error) => {
                message.error("添加失败");
                instance.pageLoading(false);
            });
    }

    updateRole() {
        if (this.state.roleSelectedRowKeys.length === 0) {
            message.warning("请选择角色");
            return;
        }

        let instance = this;
        instance.pageLoading(true);
        ajax.post('/userCenter/role/editRoleInfo', qs.stringify({
            id: this.state.roleSelectedRowKeys[0],
            name: this.state.roleModel.roleName
        }))
            .then((resource) => {
                instance.pageLoading(false);
                if (resource.data.result) {
                    message.info("修改成功");
                    instance.hideRoleModal();
                    instance.finaAllRole();
                } else {
                    message.error("修改失败");
                }
            })
            .catch((error) => {
                message.error("修改失败");
                instance.pageLoading(false);
            });
    }

    pageLoading(loading) {
        this.setState({
            pageLoading: loading
        });
    }
}

export default Role;